package com.huiyuanai.servlet;

import com.huiyuanai.dao.User;
import com.huiyuanai.service.user.UserService;
import com.huiyuanai.service.user.UserServiceImpl;
import com.huiyuanai.util.Constans;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: liwan
 * @Description: 登录
 * @Date: create in 2021/10/4
 */
public class LogIn extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("**************************login start**************************");
        //获取用户输入的用户名和密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        //调用service层方法 获得数据库数据
        UserService userService = new UserServiceImpl();
        try {
            User user = userService.logIn(userCode);
            if (user != null && userPassword.equals(user.getUserPassword())) {
                //如果正确就存到session里面
                req.getSession().setAttribute(Constans.USER_SESSION, user);
                //正确或者错误都要跳转页面
                resp.sendRedirect("/jsp/frame.jsp");
            } else {
                //错误消息
                req.setAttribute("error", "用户名或密码不正确");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
